#!/usr/bin/env python3
"""
检查 MongoDB 中对话记录的实际数据结构
"""

import asyncio
import sys
import os
import json
from datetime import datetime

# 添加项目根目录到 Python 路径
sys.path.append(os.path.dirname(os.path.abspath(__file__)))

from src.config import load_config
from src.database.manager import DatabaseManager

async def inspect_mongodb_structure():
    """检查 MongoDB 中对话记录的数据结构"""
    print("=== 检查 MongoDB 对话记录结构 ===")
    
    # 初始化数据库管理器
    config = load_config()
    db_manager = DatabaseManager(config)
    
    try:
        await db_manager.initialize()
        print("✅ 数据库连接初始化成功")
        
        mongodb_client = db_manager.mongodb_client
        
        # 获取用户对话记录
        user_conversations = await mongodb_client.get_conversations_by_user("default_user", limit=5)
        print(f"\n获取到 {len(user_conversations)} 个对话记录")
        
        for i, conv in enumerate(user_conversations):
            print(f"\n=== 对话 {i+1} ===")
            print(f"ID: {conv.get('_id')}")
            print(f"conversation_id: {conv.get('conversation_id')}")
            print(f"user_id: {conv.get('user_id')}")
            print(f"title: {conv.get('title')}")
            print(f"created_at: {conv.get('created_at')}")
            print(f"updated_at: {conv.get('updated_at')}")
            
            # 检查消息字段
            messages = conv.get('messages', [])
            print(f"messages 字段类型: {type(messages)}")
            print(f"messages 数量: {len(messages) if isinstance(messages, list) else 'N/A'}")
            
            if messages and isinstance(messages, list):
                print("前3条消息:")
                for j, msg in enumerate(messages[:3]):
                    print(f"  消息 {j+1}:")
                    print(f"    类型: {type(msg)}")
                    if isinstance(msg, dict):
                        print(f"    role: {msg.get('role')}")
                        content = msg.get('content', '')
                        print(f"    content: {content[:100]}..." if len(content) > 100 else f"    content: {content}")
                        print(f"    timestamp: {msg.get('timestamp')}")
                    else:
                        print(f"    内容: {str(msg)[:100]}")
            
            # 检查其他可能的内容字段
            other_fields = []
            for key, value in conv.items():
                if key not in ['_id', 'conversation_id', 'user_id', 'title', 'created_at', 'updated_at', 'messages']:
                    other_fields.append(f"{key}: {type(value)}")
            
            if other_fields:
                print(f"其他字段: {', '.join(other_fields)}")
            
            print("-" * 50)
        
        # 检查是否有单独的消息集合
        print("\n=== 检查消息集合 ===")
        try:
            messages_collection = mongodb_client.get_collection('conversation_messages')
            sample_messages = await messages_collection.find({"conversation_id": {"$exists": True}}).limit(5).to_list(length=5)
            
            print(f"conversation_messages 集合中有 {len(sample_messages)} 条样本消息")
            
            for i, msg in enumerate(sample_messages):
                print(f"\n消息 {i+1}:")
                print(f"  _id: {msg.get('_id')}")
                print(f"  conversation_id: {msg.get('conversation_id')}")
                print(f"  role: {msg.get('role')}")
                content = msg.get('content', '')
                print(f"  content: {content[:100]}..." if len(content) > 100 else f"  content: {content}")
                print(f"  timestamp: {msg.get('timestamp')}")
                
        except Exception as e:
            print(f"检查消息集合失败: {e}")
        
        # 统计各个集合的文档数量
        print("\n=== 集合统计 ===")
        collections = ['conversations', 'conversation_messages', 'memories', 'events', 'knowledge_nodes']
        
        for coll_name in collections:
            try:
                collection = mongodb_client.get_collection(coll_name)
                count = await collection.count_documents({})
                print(f"{coll_name}: {count} 个文档")
            except Exception as e:
                print(f"{coll_name}: 检查失败 - {e}")
        
    except Exception as e:
        print(f"❌ 检查过程中发生错误: {e}")
        import traceback
        traceback.print_exc()
    finally:
        await db_manager.close()
        print("\n数据库连接已关闭")

if __name__ == "__main__":
    asyncio.run(inspect_mongodb_structure())